package com.itdl.file.impl;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itdl.condition.FastDfsCondition;
import com.itdl.dto.fastdfs.UploadResponseDTO;
import com.itdl.file.IFileOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;

/**
 * @author: itdl
 * @date: 2022/3/7 14:20
 * @description: fastdfs实现文件操作
 * @version: 1.0
 */
@Component
@Conditional(FastDfsCondition.class)
public class FastDfsFileOperator implements IFileOperator {
    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Override
    public UploadResponseDTO upload(byte[] bytes, long fileSize, String originFileName) {
        // 创建输入流
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);

        // 获取文件后缀
        String fileSuffix = originFileName.substring(originFileName.lastIndexOf(".") + 1);

        // 执行文件上传
        StorePath storePath = fastFileStorageClient.uploadFile(inputStream, fileSize, fileSuffix, null);

        return new UploadResponseDTO(storePath.getFullPath(), fileSuffix, fileSize);
    }

    @Override
    public byte[] download(String fileId) {
        // 下载文件到字节数组中
        return fastFileStorageClient.downloadFile(
                fileId.substring(0, fileId.indexOf("/")),
                fileId.substring(fileId.indexOf("/") + 1),
                new DownloadByteArray());
    }
}
